package com.java.dao.impl;

import com.java.bean.Grade;
import com.java.bean.Student;
import com.java.dao.GradeDao;
import com.java.util.DruidUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * @Author: wjr
 * @Description:
 * @Date Created in  2020-09-09 2:26
 * @Modified By:
 */
public class GradeDaoImpl extends DruidUtil implements GradeDao {
    @Override
    public Grade findGradeById(int gid) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet rs = null;
        Grade grade = new Grade();
        ArrayList<Student> students = new ArrayList<>();
        String sql = "select * from student s,grade g where s.gid=g.gradeid and g.gradeid=?";

        try {
            connection = getConnection();
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,gid);
            rs = preparedStatement.executeQuery();
            while (rs.next()){
                grade.setGradeId(rs.getInt("gradeid"));
                grade.setGname(rs.getString("gname"));

                Student student = new Student();
                student.setStuId(rs.getInt("stuid"));
                student.setStuName(rs.getString("stuname"));
                students.add(student);
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            close(connection,preparedStatement,rs);
        }
        //建立年级与学生的关系
        grade.setStudentList(students);
        return grade;
    }
}
